//
//  HZAddView.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/25.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SnapKit
import pop





class HZAddView: UIView {
    
    
    //父控制器
    var target:UIViewController?
    
    
    // pilst 文件的数组
    lazy var array:[HZComposeModel] = {
        
       
        let array = self.giveArray()
    
        return array
    }()
    
    
    //按钮的数组
    lazy var btns:[HZAddButton] = []
        
        


     override init(frame: CGRect) {
        super.init(frame: frame)
        
//        backgroundColor = UIColor.blueColor()
        
        
        setupUI()
        
    }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
    
    
  
    
    
    private func giveArray() -> [HZComposeModel]{
        
        //获取本地的 pilst数据
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let arr = NSArray(contentsOfFile: path)!
        
        
        
        var arrM:[HZComposeModel] = []
        
        //遍历字典转模型
        for value in arr {

            
            let model = HZComposeModel(dict: value as! [String:AnyObject])
            
            arrM.append(model)
        }
        
//        print(arrM)
        
        return arrM
    }
    

    //添加子控件
    private func setupUI(){
        
          //获取屏幕截图
        let img = giveImg().applyLightEffect()
  
        //使用苹果官方的分类弄出毛玻璃样式的模糊效果
        let icon = UIImageView(image: img)

        //添加毛玻璃
        addSubview(icon);
        
        
        //添加标题文字
        addSubview(momentImg);
        
        
//        约束
        momentImg.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(icon.snp_centerX)
            make.top.equalTo(self).offset(100)
            
        }
        
        //循环添加按钮
        addBtn()
        
        
    }
    
    //循环添加按钮
    private func addBtn(){
        
        //计算出按钮之间的间隙
        let magin = (screenWidth-3*80)/4
        let w = 80
        let h = 110
        
        for (i,value) in array.enumerate() {
            
//            print(value.icon)
            
            let btn = HZAddButton()
            
            //监听按钮点击
            btn.addTarget(self, action: "didClick:", forControlEvents: .TouchUpInside)
            
            //设置按钮的 tag
            btn.tag = i;
            
            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            btn.titleLabel?.font = UIFont.systemFontOfSize(14)
            btn.setTitle(value.title, forState: .Normal)
            btn.setImage(UIImage(named: value.icon!), forState:.Normal)
            
            let row = i/3
            let column = i%3
            
            btn.frame.size = CGSize(width: w, height: h)
            btn.frame.origin.x = CGFloat(w)*CGFloat(column)+CGFloat((column+1))*magin
            btn.frame.origin.y = (CGFloat(h)+magin)*CGFloat(row)+screenHight
            
               btns.append(btn)
            
            addSubview(btn)
            
         
            
        }
    }
    
    
    
    func show(target: UIViewController?) {
//        target?.view.addSubview(self)
        // 记录外界传入的target
        self.target = target
    }
    
    // MARK: -  按钮点击事件
    @objc private func didClick(btn:HZAddButton){
        
//        print("点击了")
        
        
        //点击按钮是让按钮以动画的显示放大和缩小
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.btns {
                
                 value.alpha = 0.01
                
                //是点击的按钮就让他放大的消失
                if value == btn {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    
                    //不是点击的按钮就让他缩小的消失
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                    
                }
            }

            
            }) { (_) -> Void in
                //点击按钮的动画完毕之后
                
                //跳转指定的控制器
                
                //先获取类名的字符串
                
                
                
                let className = self.array[btn.tag].className!
                
                //                print(className)
                
                
                
                //生成类名
            let type = NSClassFromString(className)! as! UIViewController.Type
                
                //创建控制器
                let vc = type.init()
                
                self.target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                })
                
                
        }
        

        
    }
    
    
    //全屏截图
    private func giveImg()->UIImage{
        
        let size = UIScreen.mainScreen().bounds.size
        
        let rect = UIScreen.mainScreen().bounds;
        
        let window = UIApplication.sharedApplication().keyWindow!
        
    
        
        //开启图形上下文
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        
        //全屏截图
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
        
        //获取图形上下文中的图片
        let img = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图形上下文 
        UIGraphicsEndImageContext()
        
        
        return img;
    }
    
    
    
 
    // MARK: -  按钮出现动画效果
    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        
        
        for(index,value) in btns.enumerate(){
            
            animBtn(index, value: value, isUp: true)
            
        }
      

        
    }
  
    
    //点击屏幕
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        
        //按钮先动画消失
        for(index,value) in btns.reverse().enumerate(){

      
        animBtn(index, value: value, isUp: false)
        
        }
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            //自己销毁
            self.removeFromSuperview()
        }
        
    }
    
    deinit{

    }

    //按钮的动画效果
    private func animBtn(index:Int,value:HZAddButton,isUp:Bool){
        
        //初始化动画对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        //指定动画结束的位置
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x , y: value.center.y+(isUp ? -350 : 350)))
        
//         print(anim.toValue)
        
        //设置一些动画属性
        //弹性
        anim.springBounciness = 8;
        //速率
        anim.springSpeed = 10;
        
        //获取系统的决定时间
        let time = CACurrentMediaTime()
        
        //设置动画的开始时间
        anim.beginTime = Double(index)*0.025+time
        
       
        
        //添加动画到按钮上去
        value.pop_addAnimation(anim, forKey: nil)
        
        
    }
    
    
    
    
    // MARK: -  懒加载子控件
    lazy var momentImg:UIImageView = {
        
       let momentImg = UIImageView(image: UIImage(named: "compose_slogan"))
        
        momentImg.sizeToFit()
        
        return momentImg
    }()
    
    
    
    
    
    
}
